/*
 * @(#)LinkopingUniversity.java	11/06/02
 * Copyleft 2011. All rights reversed.
 *
 * This file is part of AverageGrade.
 *
 * AverageGrade is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * AverageGrade is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with AverageGrade. If not, see <http://www.gnu.org/licenses/>.
 */

package net.grade.averagegrade.parse.university;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.grade.averagegrade.parse.CourseEntriesParser;
import net.grade.averagegrade.parse.CourseEntry;
import net.grade.averagegrade.util.Utilities;

/**
 * The <code>CourseEntriesParser</code> for Linköping University. Study results can
 * be found at the student portal website (https://www3.student.liu.se/portal/eng),
 * where login is also required. Matching and extraction is performed using a
 * regular expression.
 */
public class LinkopingUniversity implements CourseEntriesParser, University {

    /** The matcher for the regular expression that is used to match course entries. */
    private final Matcher entryMatcher = Pattern.compile("(\\w{6})\\*\\s*([ /\\-\\.,a-zåäöA-ZÅÄÖ_0-9]+)" +
            "\\s*(\\d+\\.\\d)\\s*(\\d)\\s*(\\d{4}\\-\\d{2}\\-\\d{2})").matcher("");

    public CourseEntry[] extractEntries(final String text) {
        final List<CourseEntry> courseEntries = new ArrayList<CourseEntry>();

        entryMatcher.reset(text);
        while(entryMatcher.find()) {
            final String dateInfo = entryMatcher.group(5);
            final Date entryDate = Utilities.getDate(Integer.parseInt(dateInfo.substring(0, 4)),
                    Integer.parseInt(dateInfo.substring(5, 7)) - 1, Integer.parseInt(dateInfo.substring(8, 10)));

            courseEntries.add(new CourseEntry.Builder(Double.parseDouble(entryMatcher.group(3)),
                    CourseEntry.Grade.parseGrade(entryMatcher.group(4))).code(entryMatcher.group(1)).
                    name(entryMatcher.group(2)).date(entryDate).build());
        }

        return courseEntries.toArray(new CourseEntry[courseEntries.size()]);
    }

    public boolean containsEntries(final String text) {
        return (text != null && !text.isEmpty() && entryMatcher.reset(text).find());
    }

    public String getName() {
        return "Linköping University";
    }

    public String getShortName() {
        return "LiU";
    }
}